<template>
  <div>
    <el-dialog
        v-model="props.updateDialog"
        title="修改生产工序"
        width="60%"
        :before-close="handleClose"
        align-center
    >
      <el-form :model="detailsData" label-width="120px" style="padding-bottom: 5px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="工序编码" prop="processCode">
              <el-input v-model="detailsData.processCode" placeholder="请输入工序编码" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 20px">
            <el-form-item label="工序名称" prop="processName">
              <el-input v-model="detailsData.processName" placeholder="请输入工序名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否启用" prop="isEnabled">
              <el-radio-group v-model="detailsData.isEnabled">
                <el-radio label="true" value="0">是</el-radio>
                <el-radio label="false" value="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>
        <el-form-item label="工序说明">
          <el-input v-model="detailsData.processDescription" type="textarea" rows="2" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="detailsData.remark" type="textarea" rows="2" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>

      <el-divider class="section-title">
        操作步骤
      </el-divider>
      <div class="steps-section">
        <div class="table-toolbar">
          <div>
            <el-button type="primary" size="small" @click="handleAddStep" plain>
              新增
            </el-button>
            <el-button type="success" size="small" :disabled="select_order_number!=1" @click="handleEdit" plain>
              修改
            </el-button>
            <el-button type="danger" size="small" :disabled="select_order_number==0" @click="handleDelete" plain>
              删除
            </el-button>
            <el-button size="small" @click="handleExport" plain>
              导出
            </el-button>
          </div>
          <div>
            <el-button size="small" @click="handleRefresh" :icon="Refresh" circle/>
          </div>
        </div>
        <el-table :data="detailsData.processDetails" ref="multipleTable" style="width: 100%" max-height="200px"
                  :header-cell-style="{'text-align':'center','font-size':'13px'}"
                  :cell-style="{'text-align':'center','font-size':'13px'}"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column label="顺序编号" prop="orderNumber" width="100"/>
          <el-table-column label="步骤说明" prop="stepsDescription"/>
          <el-table-column label="辅助设备" prop="auxiliaryEquipment"/>
          <el-table-column label="辅助材料" prop="auxiliaryMaterials"/>
          <el-table-column label="备注" prop="remark"/>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button type="primary" size="small" link @click="handleEdit(scope.row)">
                修改
              </el-button>
              <el-button type="danger" size="small" link @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
      </template>
    </el-dialog>
    <add-details-dialog :dialogVisible="dialogVisible" :code="props.id" @details_close="DetailsClose"/>
    <updateDetailsDialog :dialogUpdate="dialogUpdate" :form="multipleSelection" @details_close="DetailsClose"/>
  </div>
</template>

<script setup>
import {reactive, ref, watch} from 'vue'
import {Refresh} from "@element-plus/icons-vue";
import {deleteDetails, findDetails, updateProcessSetting} from "@/apis/zyj/ProcessSettings.js";
import AddDetailsDialog from "./DetailsAddDialog.vue"
import updateDetailsDialog from "./updateDetailsDialog.vue"
import {ElMessage, ElMessageBox} from "element-plus";

const props = defineProps({
  id: Array,
  updateDialog: Boolean
})

const detailsData = reactive({
  processCode: '',
  processName: '',
  isEnabled: '',
  processDescription: '',
  remark: '',
  autoGenerate: false,
  processDetails: []
});

// 监听id的变化
watch(() => props.updateDialog, async (newValue) => {
  await refresh()
})

//重新查询数据
const refresh = () => {
  findDetails(props.id).then(res => {
    console.log("date", res)
    Object.assign(detailsData, res)
  })
}

const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogUpdate = ref(false)

const select_order_number = ref('') //表格select选中的条数
const select_orderId = ref([]) //表格select复选框选中的id
const multipleSelection = ref()//选中行的数据
const multipleTable = ref()//用于表格多选框选中的清理

const emit = defineEmits(['close'])
const handleClose = () => {
  emit('close')
}

const handleConfirm = () => {
  updateProcessSetting(detailsData).then(req => {
    if (req === '成功') {
      handleClose()
      ElMessage.success('修改成功')
    } else {
      ElMessage.error('修改失败')
    }
  })
}

const handleRefresh = () => {
  refresh()
}

const handleAddStep = () => {
  dialogVisible.value = true
}


const handleExport = () => {
  ElMessage.success('导出按钮')
}

const handleEdit = (row) => {
  console.log(row)
  if (row.id != null) {
    multipleSelection.value = {...row}
  } else {
    multipleSelection.value = {...multipleSelection.value[0]}
  }
  dialogUpdate.value = true
}

const handleDelete = (row) => {
  if (row.id != null) {
    select_order_number.value = "1";
  } else {
    select_order_number.value = multipleSelection.value.length;
  }
  ElMessageBox.confirm(
      '是否要删除 ' + select_order_number.value + '条数据',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (row.id != null) {
          select_orderId.value = [];
          select_orderId.value.push(row.id)
        }
        deleteDetails(select_orderId.value).then((res) => {
          if (res == '成功') {
            refresh()
            ElMessage.success('成功删除: ' + select_order_number.value + '条数据')
            select_order_number.value = 0;
            select_orderId.value = [];
            multipleTable.value.clearSelection();
          } else {
            ElMessage.error('系统错误！删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}

const handleSelectionChange = (rows) => {
  // 解决来回切换页面，也无法清除上次选中情况
  multipleSelection.value = rows;
  select_order_number.value = multipleSelection.value.length;
  select_orderId.value = [];
  if (rows) {
    rows.forEach((row) => {
      if (row) {
        select_orderId.value.push(row.id);
      }
    });
  }
}

const DetailsClose = () => {
  dialogVisible.value = false
  dialogUpdate.value = false
  refresh()
}
</script>

<style scoped>
.steps-section {
  padding: 20px;
  font-size: 14px;
}

.section-title {
  margin: 24px 0;
}

.table-toolbar {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.total {
  margin-right: 16px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>